package com.ticketbox.web.servlets;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
@WebFilter(filterName = "AuthFilter", urlPatterns = {"*.jsp"})
public class AuthFilter implements Filter {
     
    public AuthFilter() {
    }
 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
         try {
 
            // check whether session variable is set
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession ses = req.getSession(false);
            //  allow user to proccede if url is login* or user logged in or user is accessing any page in //public folder
            String reqURI = req.getRequestURI();
            if ( reqURI.indexOf("/login.jsp") >= 0 || (ses != null && ses.getAttribute("username") != null) )
            	chain.doFilter(request, response);
            else   // user didn't log in but asking for a page that is not allowed so take user to login page
            	res.sendRedirect(req.getContextPath() + "/login.jsp");
      }
     catch(Throwable t) {
         System.out.println( t.getMessage());
     }
    }

	public void destroy() {
		
	}



	public void init(FilterConfig arg0) throws ServletException {
		
	}
 

}